const htmlWebpackPlugin = require('html-webpack-plugin')

class InlineSourcePlugin {
  constructor ({ match }) {
    this.exp = match
  }

  processTag (tag, compilation) {
    let newTag
    let url
    console.log(tag.tagName)
    if (tag.tagName === 'link' && this.exp.test(tag.attributes.href)) {
      newTag = {
        tagName: 'style',
        attributes: { type: 'text/css' }
      }
      url = tag.attributes.href
    }
    if (tag.tagName === 'script' && this.exp.test(tag.attributes.src)) {
      newTag = {
        tagName: 'script',
        attributes: { type: 'application/javascript' }
      }

      url = tag.attributes.src
    }

    if (url) {
      newTag.innerHTML = compilation.assets[url].source()
      delete compilation.assets[url]
      return newTag
    }

    return tag

  }

  processTags (data, compilation) {
    const headTags = []
    const bodyTags = []
    // const { headTags, bodyTags } = data

    data.headTags.forEach(tag => {
      headTags.push(this.processTag(tag, compilation))

    })

    data.bodyTags.forEach(tag => {
      bodyTags.push(this.processTag(tag, compilation))
    })

    return { ...data, headTags, bodyTags }
  }

  apply (compiler) {
    compiler.hooks.compilation.tap('InlineSourcePlugin', (compilation) => {
      console.log('----------------------111111')
      htmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync('afterPlugin', (data, cb) => {
        console.log('----------------------222222')
        data = this.processTags(data, compilation)
        cb(null, data)
      })
    })
  }
}

module.exports = InlineSourcePlugin
